package com.tigercel.xiangchengyun.ui.fragments

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.GridView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.tigercel.xiangchengyun.R
import com.tigercel.xiangchengyun.adapter.GridViewAdpter
import com.tigercel.xiangchengyun.adapter.GridViewPagerAdapter
import com.tigercel.xiangchengyun.adapter.ServiceListAdapter
import com.tigercel.xiangchengyun.adapter.ServicesRecyclerViewAdapter
import com.tigercel.xiangchengyun.entity.ProdctBean
import com.tigercel.xiangchengyun.entity.ServiceEntity
import com.tigercel.xiangchengyun.ui.activities.WebViewActivity
import com.tigercel.xiangchengyun.ui.custom.lbanners.utils.ScreenUtils
import com.tigercel.xiangchengyun.ui.custom.verticaltablayout.util.DisplayUtil
import com.tigercel.xiangchengyun.utils.JsonUtil
import kotlinx.android.synthetic.main.fragment_services.*
import kotlinx.android.synthetic.main.grid_service_layout.*
import kotlinx.android.synthetic.main.include_titlebar.*
import org.jetbrains.anko.support.v4.toast
import com.tigercel.xiangchengyun.utils.Global
/**
 * 服务界面
 */
class ServicesFragment : Fragment() {
    private var proName: MutableList<String>? = null
    private var totalPage: Int = 1 //总的页数，默认1页
    private var mPageSize: Int = 4 //每页显示的最大的数量
    private lateinit var listDatas: MutableList<ProdctBean>
    private lateinit var servicesDatas: MutableList<ServiceEntity>
    private lateinit var servicesAllDatas: MutableList<List<ServiceEntity>>
    private lateinit var viewPagerList: MutableList<View>
    private var mIndicatorWidth = 7//默认指示器大小
    private var mSelectIndicatorRes = R.drawable.page_indicator_select//选中指示器
    private var mUnSelectIndicatorRes = R.drawable.page_indicator_unselect//未选中指示器
    private var pageItemWidth: Int = 0
    private var adapter: ServicesRecyclerViewAdapter? = null
    private var controller: FragmentController? = null

    private var containerView: View? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        containerView = inflater.inflate(R.layout.fragment_services, container, false)
        return containerView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        titlebar_tv.text = "服务"
        getContent()
    }

    private fun initProductData() {

//        for (i in 0 until proName!!.size) {
//            listDatas.add(ProdctBean("", proName!![i], "http://sh.58.com/"))
//        }
        //总的页数向上取整
        totalPage = Math.ceil(listDatas.size * 1.0 / mPageSize).toInt()
        viewPagerList = ArrayList()
        for (i in 0 until totalPage) {
            //每个页面都是inflate出一个新实例
            val gridView: GridView = View.inflate(activity!!, R.layout.grid_view_layout, null) as GridView
            gridView.adapter = GridViewAdpter(activity, listDatas, i, mPageSize)
            gridView.setOnItemClickListener { _, _, i, _ ->
                val product: ProdctBean = gridView.getItemAtPosition(i) as ProdctBean
                val intent = Intent()
                intent.putExtra("title", product.name)
                intent.putExtra("url", product.url)
                intent.putExtra("id", "")
                intent.setClass(activity, WebViewActivity::class.java)
                startActivity(intent)
            }
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView)
        }

        //设置ViewPager适配器
        viewpager.layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, DisplayUtil.dp2px(activity, 130F))
        viewpager.adapter = GridViewPagerAdapter(viewPagerList)
        pageItemWidth = ScreenUtils.dip2px(context, mIndicatorWidth.toFloat())
        //添加指示器
        for (i in 0 until totalPage) {
            val view = View(context)
            if (i == 0) {
                view.isPressed = true
                //LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + ScreenUtils.dip2px(context, 3), pageItemWidth + ScreenUtils.dip2px(context, 3));
                val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                params.setMargins(pageItemWidth, 0, 0, 0)
                view.layoutParams = params
                view.setBackgroundResource(mSelectIndicatorRes)
            } else {
                val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                params.setMargins(pageItemWidth, 0, 0, 0)
                view.layoutParams = params
                view.setBackgroundResource(mUnSelectIndicatorRes)
            }

            points.addView(view)
        }

        //设置ViewPager的滑动监听，主要是设置点点的背景颜色的改变
        viewpager!!.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                val count = points.childCount
                for (i in 0 until count) {
                    val view = points.getChildAt(i)
                    if (i == position) {
                        view.isPressed = true
                        //LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pageItemWidth + ScreenUtils.dip2px(context, 3), pageItemWidth + ScreenUtils.dip2px(context, 3));
                        val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                        params.setMargins(pageItemWidth, 0, 0, 0)
                        view.layoutParams = params
                        view.setBackgroundResource(mSelectIndicatorRes)
                    } else {
                        val params = LinearLayout.LayoutParams(pageItemWidth, pageItemWidth)
                        params.setMargins(pageItemWidth, 0, 0, 0)
                        view.layoutParams = params
                        view.setBackgroundResource(mUnSelectIndicatorRes)
                    }
                }
            }
        })
    }

    private fun getContent() {
        listDatas = ArrayList()
        listDatas.clear()
        OkGo.get<String>(Global.baseUrl + Global.services)
                .tag(this)
                .params("has_desc", "1")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val result = response!!.body()
                        val status = JsonUtil.get_key_string("status", result)
                        val msg = JsonUtil.get_key_string("msg", result)
                        val code = JsonUtil.get_key_string("code", result)
                        val data = JsonUtil.get_key_string("data", result)
                        if (status == "0") {
                            val all_service = JsonUtil.getList("all_service", data)
                            val hot_service = JsonUtil.getList("hot_service", data)

                            for (i in 0 until hot_service.size) {
                                var service_id = JsonUtil.get_key_string("service_id", hot_service[i])
                                val name = JsonUtil.get_key_string("name", hot_service[i])
                                var type = JsonUtil.get_key_string("type", hot_service[i])
                                val url = JsonUtil.get_key_string("url", hot_service[i])
                                val icon = JsonUtil.get_key_string("icon", hot_service[i])
                                listDatas.add(ProdctBean(icon, name, url))
                            }
                            initProductData()
                            proName = ArrayList()
                            servicesAllDatas = ArrayList()
                            for (i in 0 until all_service.size) {
                                var name = JsonUtil.get_key_string("name", all_service[i])
                                var list = JsonUtil.getList("list", all_service[i])
                                proName!!.add(name)
                                servicesDatas = ArrayList()
                                servicesDatas!!.clear()
                                for (k in 0 until list.size) {
                                    var service_id = JsonUtil.get_key_string("service_id", list[k])
                                    var service_name = JsonUtil.get_key_string("service_name", list[k])
                                    var icon = JsonUtil.get_key_string("icon", list[k])
                                    var type = JsonUtil.get_key_string("type", list[k])
                                    var url = JsonUtil.get_key_string("url", list[k])
                                    var desc = JsonUtil.get_key_string("desc", list[k])
                                    var serviceEntity = ServiceEntity(service_id, service_name, icon, type, url, desc)
                                    if (service_name != "便民服务中心") {
                                        servicesDatas!!.add(serviceEntity)
                                    }
                                }
                                servicesAllDatas.add(servicesDatas)
                            }
                            var adapter = ServiceListAdapter(activity!!, servicesAllDatas, proName as ArrayList<String>)
                            list_container_services.adapter = adapter
                        } else {
                            toast("数据获取失败")
                        }
                    }

                })
    }
}




